package com.liveinstars.im.domain.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liveinstars.api.im.query.ChatGroupQuery;
import com.liveinstars.im.domain.dao.mapper.NewChatGroupMapper;
import com.liveinstars.im.domain.dao.model.ChatGroup;
import com.liveinstars.im.domain.manager.ChatGroupManager;
import com.onepiece.shipelves.common.enums.SystemExceptionEnum;
import com.onepiece.shipelves.common.exception.DatabaseException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;


/**
 * @author: ting
 * @date: 2020/3/3
 */
@Service("chatGroupManager")
public class ChatGroupManagerImpl extends ServiceImpl<NewChatGroupMapper, ChatGroup> implements ChatGroupManager {

    private final static Logger logger = LoggerFactory.getLogger(ChatGroupManagerImpl.class);

    private final static Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");

    @Override
    public Page<ChatGroup> pageByQuery(ChatGroupQuery query) {
        try {
            Page<ChatGroup> page = new Page<>(query.getPageNum(), query.getPageSize());
            QueryWrapper<ChatGroup> queryWrapper = constructQueryWrapperByQuery(query);
            this.page(page, queryWrapper);
            return page;
        } catch (Exception e) {
            logger.error("获取举报记录分页列表异常：{}", e.getMessage() , e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }

    @Override
    public List<ChatGroup> listByQuery(ChatGroupQuery query) {
        QueryWrapper<ChatGroup> queryWrapper = constructQueryWrapperByQuery(query);
        List<ChatGroup> list = this.list(queryWrapper);
        return list;
    }

    public QueryWrapper<ChatGroup> constructQueryWrapperByQuery(ChatGroupQuery query) {
        if (query.getHidden() == null) {
            query.setHidden(true);
        }
        QueryWrapper<ChatGroup> queryWrapper = new QueryWrapper<>();
        if (query.getBigClassId() != null) {
            queryWrapper.eq("big_class_id", query.getBigClassId());
        } else if (CollectionUtils.isNotEmpty(query.getBigClassIdList())) {
            queryWrapper.in("big_class_id", query.getBigClassIdList());
        }
        if (StringUtils.isNotEmpty(query.getSearchName())) {
            if (isInteger(query.getSearchName())) {
                query.setHidden(false);
                queryWrapper.and(queryWrapper1 -> queryWrapper1.like("name", query.getSearchName())
                        .or(queryWrapper2 -> queryWrapper2.eq("id", query.getSearchName())));
            } else {
                queryWrapper.like("name", query.getSearchName());
            }
        }
        if (StringUtils.isNotEmpty(query.getChatGroupName())) {
            queryWrapper.eq("name", query.getChatGroupName());
        }
        if (query.getGroupType() != null) {
            queryWrapper.eq("group_type", query.getGroupType());
        }
        if (query.getHot() != null) {
            queryWrapper.ge("hot", query.getHot());
        }
        if (CollectionUtils.isNotEmpty(query.getIdList())) {
            query.setHidden(false);
            queryWrapper.in("id", query.getIdList());
        }
        if (query.getHidden()) {
            queryWrapper.eq("hidden", false);
        }
        if (query.getHot() != null) {
            queryWrapper.orderByDesc("hot");
        } else {
            queryWrapper.orderByDesc("id");
        }
        return queryWrapper;
    }

    public static boolean isInteger(String str) {
        return pattern.matcher(str).matches();
    }

    @Override
    public ChatGroup getById(Long id) {
        try {
            ChatGroup chatGroup = super.getById(id);
            return chatGroup;
        } catch (Exception e) {
            logger.error("根据id获取圈子详情异常：{}", e.getMessage() , e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }

    @Override
    public boolean updateById(ChatGroup chatGroup) {
        try {
            return super.updateById(chatGroup);
        } catch (Exception e) {
            logger.error("根据id更新圈子信息异常：{}", e.getMessage() , e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            this.removeById(id);
        } catch (Exception e) {
            logger.error("根据id删除圈子信息异常：{}", e.getMessage() , e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }

    @Override
    public List<ChatGroup> listByCreateUserId(Long userId) {
        QueryWrapper<ChatGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_by_id", userId).eq("group_type", 0);
        List<ChatGroup> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public ChatGroup getFriendsChatGroup(Long userIdA, Long userIdB) {
        try {
            QueryWrapper<ChatGroup> queryWrapper = new QueryWrapper<>();
            setPersonToPersonGroupUserId(queryWrapper, userIdA, userIdB);
            queryWrapper.eq("group_type", 3)
                    .orderBy(true, true, "id");
            List<ChatGroup> list = this.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                return list.get(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error("获取点聊圈子信息异常getFriendsChatGroup：params:{} errorMsg:{}",
                    "userIdA=" + userIdA + ", userIdB=" + userIdB,
                    e.getMessage() , e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }

    @Override
    public ChatGroup createFriendsChatGroup(Long applyUserId, Long acceptUserId) {
        ChatGroup friendsChatGroup = this.getFriendsChatGroup(applyUserId, acceptUserId);
        try {
            if (friendsChatGroup == null) {
                friendsChatGroup = new ChatGroup();
                friendsChatGroup.setCreateById(applyUserId);
                friendsChatGroup.setPersonToPersonGroupUserId(applyUserId, acceptUserId);
                friendsChatGroup.setGroupType(3);
                friendsChatGroup.setCreateDate(Long.valueOf(System.currentTimeMillis()/1000).intValue());
                this.save(friendsChatGroup);
            }
            return friendsChatGroup;
        } catch (Exception e) {
            logger.error("createFriendsChatGroup：params:{} errorMsg:{}",
                    "applyUserId=" + applyUserId + ", acceptUserId=" + acceptUserId,
                    e.getMessage() , e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }

    @Override
    public Integer countCreateChatGroupByUserId(Long userId) {
        QueryWrapper<ChatGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_by_id", userId).eq("group_type", 0);
        int count = this.count(queryWrapper);
        return count;
    }

    @Override
    public List<ChatGroup> listByCreateUserIdAndInterestId(Long userId, Integer interestId) {
        QueryWrapper<ChatGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_by_id", userId).eq("group_type", 0).eq("interest_id", interestId);
        List<ChatGroup> list = this.list(queryWrapper);
        return list;
    }

    public void setPersonToPersonGroupUserId(QueryWrapper<ChatGroup> queryWrapper, Long userIdA, Long userIdB) {
        if (userIdA > userIdB) {
            queryWrapper.eq("manager1_id", userIdA);
            queryWrapper.eq("manager2_id", userIdB);
        } else {
            queryWrapper.eq("manager1_id", userIdB);
            queryWrapper.eq("manager2_id", userIdA);
        }
    }
}
